在準備寫這個遊戲前,腦海中浮現需要用到的元素:
在撰寫的過程中,遇到不清楚html語法 <input type="submit">
和<button>
的差異,這兩者外觀上看起來一樣,在w3school查到的資訊如下:
<input type="submit"> defines a button for submitting form data to a form-handler.
The form-handler is typically a server page with a script for processing input data.
The <button> tag defines a clickable button.
Inside a <button> element you can put text (and tags like <i>, <b>, <strong>, <br>, <img>, etc.). That is not possible with a button created with the <input> element!
我的解讀是,input的submit,是會需要跟<form>
搭配,會送出整個<form>
裡的資料,而button外觀上不只是預設看到那種銀灰色按鈕,他還可以是一張圖片,或是html上的純文字形式 (這部分若有理解錯誤的話,請各位大大指點)
目前寫了一個初版,寫的很陽春為了判斷B的數量,把猜的數字和目標值都各對應陣列[0]~[9],計算數字出現的次數,這缺點是要掃陣列且浪費空間,因為有點像是稀疏矩陣,但就是個雛形,之後會不定期做優化
細節:
<body>
<label>Guess the number </label> <br>
<input id="guess_v" type="text" placeholder="Enter 4 digtis numbers">
<input id="submit" type="submit" value="submit">
<button id="hint">hint</button>
<div class="hint"></div>
<div class="history">
<h3>History</h3>
<div class="his_content"></div>
</div>
</body>
有個猜測的輸入框、提示區,歷史紀錄區
let btn = document.getElementById('submit');
btn.addEventListener('click', getGuess); // 當按下submit後,呼叫getGuess() function
function getGuess() {
let history = document.querySelector('.his_content');
let guess_n = document.getElementById("guess_v").value;
ori = history.innerHTML;
/*註解區域: 舊的紀錄在最上面,新的紀錄一直往下長*/
//history.innerHTML = ori + guess_n + "<br>";
//history.innerHTML += judge(guess_n);
/*新的紀錄更新在最上面*/
history.innerHTML = guess_n + ", result: " + judge(guess_n) + ori + "<br>";
}
let round = 0;
const tar_arr = [];
const guess_arr = [];
function judge(guess_n)
{
let ans = "";
round += 1; // 記錄總共猜了幾回合
if (guess_n === tar)
{
alert("bingo!!! the target number is: " + tar + ", total guess " + round + " times");
location.reload();
init();
}
else
{
let A = 0;
// 分別
for (let i = 0; i<10; i++)
{
tar_arr[i] = 0;
guess_arr[i] = 0;
}
// 掃完猜測值與答案,即可知道A的數量
for (let i = 0; i<4; i++)
{
if (guess_n[i] === tar[i])
{
A += 1;
}
else // 掃的過程中,當A不成立,則分別記錄這個位置猜測的數值與目標的數值,其出現次數。
{
guess_arr[Number(guess_n[i])] += 1;
tar_arr[Number(tar[i])] += 1;
}
}
let B = 0
// 掃過[0]~[9]在猜測數值和目標數值的次數,即可知道B的數量
for (let i = 0; i<10; i++)
{
while (guess_arr[i] > 0 && tar_arr[i] > 0)
{
B += 1;
guess_arr[i] -= 1;
tar_arr[i] -= 1;
}
}
ans = A + "A" + B + "B<br>";
}
return ans;
}
history.innerHTML
,再透過字串相加寫進 history.innerHTML
location.reload();
,或許可以設計清除所有資訊的按鈕,或猜測成功後自動呼叫此功能